﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TaoNiuOA.Models;
using PagedList;

namespace TaoNiuOA.Web.Controllers
{
    /// <summary>
    /// 用户中心
    /// </summary>
    public class UCenterController : Controller
    {
        private DbEntity db = new DbEntity();

        //分页记录数
        int pageSize = 30;

        [IsLogon]
        public ViewResult Index()
        {
            return View(db.Users.ToList());
        }

        #region 个人信息

        //个人信息
        [IsLogon]
        public ViewResult MyInfo()
        {
            var u = Session["users"] as TaoNiuOA.Models.User;

            return View(u);
        }

        //更新个人信息
        [IsLogon]
        [HttpPost]
        public ActionResult MyInfo(User user, FormCollection fc)
        {
            //更新基本信息
            var u = Session["users"] as TaoNiuOA.Models.User;
            db.Entry(user).State = EntityState.Modified;
            user.UserName = u.UserName;
            user.Password = u.Password;
            user.Email = fc["Email"];
            user.PasswordQuestion = fc["PasswordQuestion"];
            user.PasswordAnswer = u.PasswordAnswer;
            user.RegTime = u.RegTime;
            user.LastActivityTime = u.LastActivityTime;
            user.UserInfoID = u.UserInfoID;
            user.DepartmentID = u.DepartmentID;
            user.UserGroupID = u.UserGroupID;
            user.Status = u.Status;
            db.SaveChanges();

            //更新关联的userInfoes表

            var userSql = string.Format("update [userInfoes] set ");
            var userInfo = db.UserInfoes.SingleOrDefault(n => n.UserInfoID == user.UserInfoID);
            db.Entry(userInfo).State = EntityState.Modified;
            userInfo.Name = fc["Name"];
            userInfo.Sex = Convert.ToBoolean(fc["Sex"]);
            if (!string.IsNullOrEmpty(fc["Birthday"]))
                userInfo.Birthday = Convert.ToDateTime(fc["Birthday"]);
            userInfo.Tel = fc["Tel"];
            userInfo.Mobile = fc["Mobile"];
            userInfo.QQ = fc["QQ"];
            userInfo.Msn = fc["Msn"];
            userInfo.Id = fc["Id"];
            userInfo.BankName = fc["BankName"];
            userInfo.BankAccount = fc["BankAccount"];
            userInfo.Address = fc["Address"];
            userInfo.Postcode = fc["Postcode"];
            db.SaveChanges();

            //保存成功后更新session
            u = db.Users.Find(user.UserID);
            Session["users"] = u;
            return View(u);
        }
        #endregion

        #region 个人任务

        [IsLogon]
        public ActionResult MyTask(int? page)
        {
            var u = Session["users"] as TaoNiuOA.Models.User;

            var index = (page ?? 1) - 1;

            var mod = Request.QueryString["mod"];
            ViewData["mod"] = mod;

            //默认,我的任务
            var list = db.Tasks.Where(n => n.UserID == u.UserID).OrderByDescending(n => n.Level).ToPagedList(index, pageSize);
            switch (mod)
            {
                //执行中的
                case "executing":
                    list = db.Tasks.Where(n => n.Status == 2).OrderBy(n => n.Level).ToPagedList(index, pageSize);
                    break;
                //已完成的
                case "finish":
                    list = db.Tasks.Where(n => n.Status == 3).OrderBy(n => n.Level).ToPagedList(index, pageSize);
                    break;
                default:
                    break;
            }

            return View(list);
        }

        [IsLogon]
        [HttpPost]
        public ActionResult MyTask(User user)
        {
            return View();
        }

        //桃牛任务列表
        [IsLogon]
        public ViewResult TaskList(int? page)
        {
            var index = (page ?? 1) - 1;
            var mod = Request.QueryString["mod"];
            ViewData["mod"] = mod;

            //默认,所有任务
            var list = db.Tasks.OrderBy(n => n.Level).ToPagedList(index, pageSize);
            switch (mod)
            {
                //未被领取
                case "notTake":
                    list = db.Tasks.Where(n => n.Status == 0).ToPagedList(index, pageSize);
                    break;
                //已被领取
                case "take":
                    list = db.Tasks.Where(n => n.Status == 1).OrderBy(n => n.Level).ToPagedList(index, pageSize);
                    break;
                //执行中的
                case "executing":
                    list = db.Tasks.Where(n => n.Status == 2).OrderBy(n => n.Level).ToPagedList(index, pageSize);
                    break;
                //已完成的
                case "finish":
                    list = db.Tasks.Where(n => n.Status == 3).OrderBy(n => n.Level).ToPagedList(index, pageSize);
                    break;
                //默认,所有任务
                default:
                    break;
            }

            return View(list);
        }

        //任务详细
        [IsLogon]
        public ViewResult TaskDetails(int id)
        {
            Task task = db.Tasks.Find(id);
            //显示任务评级
            var isg = "还未评级";
            if (task.Status == 3)
            {
                if (task.IsGood != null)
                {
                    if (Convert.ToBoolean(task.IsGood))
                        isg = "合格";
                    else
                        isg = "不合格";
                }
            }
            ViewBag.IsGood = isg;
            return View(task);
        }

        //获取任务编辑信息
        [IsLogon]
        [HttpPost]
        public ActionResult GetMyTask(int id)
        {
            var user = Session["users"] as TaoNiuOA.Models.User;
            Task task = db.Tasks.SingleOrDefault(n => n.TaskID == id && n.UserID == user.UserID);
            var strHtml = new System.Text.StringBuilder();
            if (task == null)
                return Json("找不到记录");
            if (task.Status == 1)
            {
                strHtml = new System.Text.StringBuilder();
                strHtml.Append("<select id='mod' name='mod'>");
                strHtml.Append("<option value='executing' selected='selected'>开始执行</option>");
                strHtml.Append("</select>");
            }
            else if (task.Status == 2)
            {
                strHtml = new System.Text.StringBuilder();
                if (string.IsNullOrEmpty(task.Process))
                    strHtml.Append(@"<div>进度 <input type='text' value='' id='process' style='width:40px;' />%<br />");
                else
                    strHtml.Append(string.Format(@"<div>进度 <input type='text' value='{0}' id='process' style='width:40px;' />%<br />", task.Process.Replace("%", "")));
                strHtml.Append("<select id='mod' name='mod'>");
                strHtml.Append("<option value='null' selected='selected'></option>");
                strHtml.Append("<option value='finish'>确定完成</option>");
                strHtml.Append("</select>");
            }
            else
            {
                return Json("暂无操作");
            }
            return Json(strHtml.ToString());
        }


        [IsLogon]
        [HttpPost]
        public ActionResult EditMyTask()
        {
            try
            {
                var mod = Request.QueryString["mod"];
                var taskID = Convert.ToInt32(Request.QueryString["taskID"]);
                var process = Request.QueryString["process"];
                var user = Session["users"] as TaoNiuOA.Models.User;
                Task task = db.Tasks.SingleOrDefault(n => n.TaskID == taskID && n.UserID == user.UserID);
                if (task == null)
                    return Json("error");
                //把任务状态改为2,即执行中
                if (mod == "executing")
                {
                    db.Entry(task).State = EntityState.Modified;
                    task.Status = 2;
                    task.StartTime = DateTime.Now;
                    task.LastUpdate = DateTime.Now;
                    db.SaveChanges();
                    return Json("ok");
                }
                //编辑任务进度
                if (mod == "null")
                {
                    db.Entry(task).State = EntityState.Modified;
                    task.Process = Convert.ToInt32(process.Trim()).ToString() + "%";
                    task.LastUpdate = DateTime.Now;
                    db.SaveChanges();
                    return Json("ok");
                }
                //把任务状态改为已完成
                else
                {
                    db.Entry(task).State = EntityState.Modified;
                    task.Process = Convert.ToInt32(process.Trim()).ToString() + "%";
                    task.EndTime = DateTime.Now;
                    task.LastUpdate = DateTime.Now;
                    task.Status = 3;
                    db.SaveChanges();
                    return Json("ok");
                }
            }
            catch
            {
                return Json("error");
            }
        }

        //领取任务
        [IsLogon]
        [HttpPost]
        public ActionResult TakeTask()
        {
            Response.ContentType = "application/json";
            var taskid = Request.QueryString["id"];
            if (!ShenLan.Common.IntHandler.IsNotNullOrInt(taskid))
            {
                return Json("错误的id");
            }
            var id = Convert.ToInt32(taskid);
            var task = db.Tasks.SingleOrDefault(n => n.TaskID == id);
            if (task == null)
                return Json("找不到记录");
            //判断是否已经被领取
            if (task.Status != 0)
                return Json("该任务已经被领取");
            var u = Session["users"] as TaoNiuOA.Models.User;
            db.Entry(task).State = EntityState.Modified;
            task.LastUpdate = DateTime.Now;
            task.UserID = u.UserID;
            //把任务状态改为1,即已被领取
            task.Status = 1;
            db.SaveChanges();
            return Json("领取任务成功");
        }

        #endregion

        #region 个人考勤

        [IsLogon]
        public ViewResult MyChecking(int? page)
        {
            ViewData["actionName"] = "MyChecking";
            var index = (page ?? 1) - 1;
            var user = Session["users"] as TaoNiuOA.Models.User;

            var today = DateTime.Now.ToString("yyyy-MM-dd");
            var list = new List<Checking>();

            var mod = Request.QueryString["mod"];
            ViewData["mod"] = mod;

            //根据条件查询
            if (!string.IsNullOrEmpty(mod) && mod.IndexOf("-") != -1)
            {
                list = db.Checkings.Where(n => n.Date.Contains(mod) && n.UserID == user.UserID).OrderBy(n => n.Date).ToList();                
            }
            else
            {
                switch (mod)
                {
                    //所有
                    case "all":
                        list = (from n in db.Checkings where n.UserID == user.UserID select n).ToList();
                        break;
                    //昨天 
                    case "yesterday":
                        today = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                        list = (from n in db.Checkings where n.Date.Contains(today) && n.UserID == user.UserID select n).ToList();
                        break;
                    //本月
                    case "thismonth":
                        today = DateTime.Now.ToString("yyyy-MM");
                        list = (from n in db.Checkings where n.Date.Contains(today) && n.UserID == user.UserID select n).ToList();
                        break;
                    //上月 
                    case "lastmonth":
                        today = DateTime.Now.AddMonths(-1).ToString("yyyy-MM");
                        list = (from n in db.Checkings where n.Date.Contains(today) && n.UserID == user.UserID select n).ToList();
                        break;
                    //默认,今天
                    default:
                        list = (from n in db.Checkings where n.Date.Contains(today) && n.UserID == user.UserID select n).ToList();
                        break;
                }
            }
            return View(list.ToPagedList(index, pageSize));
        }

        #endregion

        #region 个人绩效

        [IsLogon]
        public ViewResult MyPerformance(int? page)
        {
            ViewData["actionName"] = "MyPerformance";
            var index = (page ?? 1) - 1;
            var user = Session["users"] as TaoNiuOA.Models.User;

            var month = DateTime.Now.ToString("yyyy-MM");
            var list = new List<Performance>();

            var mod = Request.QueryString["mod"];
            ViewData["mod"] = mod;

            //根据条件查询
            if (!string.IsNullOrEmpty(mod) && mod.IndexOf("-") != -1)
            {
                list = (from n in db.Performances where n.Month.Contains(mod) && n.UserID == user.UserID select n).ToList();
            }
            else
            {
                switch (mod)
                {
                    //所有
                    case "all":
                        list = (from n in db.Performances where n.UserID == user.UserID select n).ToList();
                        break;
                    //上个月 
                    case "lastmonth":
                        month = DateTime.Now.AddMonths(-1).ToString("yyyy-MM");
                        list = (from n in db.Performances where n.Month.Contains(month) && n.UserID == user.UserID select n).ToList();
                        break;
                    //默认,本月
                    default:
                        list = (from n in db.Performances where n.Month.Contains(month) && n.UserID == user.UserID select n).ToList();
                        break;
                }
            }

            //统计信息
            double totalPoint = 0;
            double payPoint = 0;
            foreach (var p in list)
            {
                totalPoint += p.TotalPoint;
                payPoint += p.PayPoint;
            }
            ViewData["statInfo"] = "统计:共" + list.Count + "条记录,应得绩效:" + totalPoint + ",实得绩效:" + payPoint;

            return View(list.ToPagedList(index, pageSize));
        }

        #endregion

        #region 个人工资

        [IsLogon]
        public ActionResult MySalary()
        {
            var u = Session["users"] as TaoNiuOA.Models.User;
            var list = db.Salaries.Where(n => n.UserID == u.UserID);
            return View(list);
        }

        [IsLogon]
        [HttpPost]
        public ActionResult MySalary(User user)
        {
            return View();
        }

        #endregion

        #region 个人申请

        [IsLogon]
        public ActionResult MyApply(int? page)
        {
            var index = (page ?? 1) - 1;
            var mod = Request.QueryString["mod"];
            ViewData["mod"] = mod;
            var user = Session["users"] as TaoNiuOA.Models.User;
            var allApplies = db.Applies.Where(n => n.UserID == user.UserID).OrderByDescending(n => n.ApplyTime);
            ViewData["allcount"] = allApplies.Count();
            ViewData["refusecount"] = allApplies.Where(n => n.Status == 0).Count();
            ViewData["agreecount"] = allApplies.Where(n => n.Status == 1).Count();
            ViewData["approvecount"] = allApplies.Where(n => n.Status == 2).Count();
            var list = new List<Apply>();
            switch (mod)
            {
                //拒绝的申请
                case "refuse":
                    list = allApplies.Where(n => n.Status == 0).ToList();
                    break;
                //同意的申请
                case "agree":
                    list = allApplies.Where(n => n.Status == 1).ToList();
                    break;
                //审批中的
                case "approve":
                    list = db.Applies.Where(n => n.Status == 2).ToList();
                    break;
                //默认,所有申请
                default:
                    list = allApplies.ToList();
                    break;
            }

            return View(list.ToPagedList(index, pageSize));
        }

        [IsLogon]
        public ActionResult MyApplyDetails(int id)
        {
            var user = Session["users"] as TaoNiuOA.Models.User;
            Apply apply = db.Applies.SingleOrDefault(n => n.ApplyID == id && n.UserID == user.UserID);
            if (apply == null)
            {
                Response.Write("<script>alert('您查看的申请不存在');window.location.href='/ucenter/myapply';</script>");
                return View(apply);
            }
            return View(apply);
        }

        // GET: 创建申请
        [IsLogon]
        public ActionResult MyApplyNew()
        {
            ViewBag.ApplyTypeID = new SelectList(db.ApplyTypes, "ApplyTypeID", "TypeName");
            return View();
        }

        // POST: 创建申请
        [IsLogon]
        [HttpPost]
        public ActionResult MyApplyNew(Apply apply)
        {
            if (ModelState.IsValid)
            {
                var user = (TaoNiuOA.Models.User)Session["users"];
                apply.Status = 2;
                apply.UserID = user.UserID;
                apply.ApplyTime = DateTime.Now;
                db.Applies.Add(apply);
                db.SaveChanges();
                return RedirectToAction("MyApply");
            }

            return View(apply);
        }

        //判断是否能编辑申请
        [IsLogon]
        [HttpPost]
        public ActionResult isCanEditApply(int id)
        {
            var user = Session["users"] as TaoNiuOA.Models.User;
            Apply apply = db.Applies.SingleOrDefault(n => n.ApplyID == id && n.UserID == user.UserID);
            if (apply == null)
            {
                return Json("记录不存在");
            }
            if (apply.Status == 1)
            {
                return Json("您编辑的申请已经审批不能再编辑");
            }
            return Json("ok");
        }

        [IsLogon]
        public ActionResult MyApplyEdit(int id)
        {
            var user = Session["users"] as TaoNiuOA.Models.User;
            Apply apply = db.Applies.SingleOrDefault(n => n.ApplyID == id && n.UserID == user.UserID);
            if (apply == null)
            {
                Response.Write("<script>alert('您编辑的申请不存在');window.location.href='/ucenter/myapply';</script>");
                return View(apply);
            }

            ViewBag.ApplyTypeID = new SelectList(db.ApplyTypes, "ApplyTypeID", "TypeName", apply.ApplyTypeID);
            if (apply.Status == 1)
            {
                Response.Write("<script>alert('您编辑的申请已经审批不能再编辑.');window.location.href='/ucenter/myapply';</script>");
                return View(apply);
            }

            return View(apply);
        }

        [IsLogon]
        [HttpPost]
        public ActionResult MyApplyEdit(Apply apply)
        {
            if (ModelState.IsValid)
            {
                db.Entry(apply).State = EntityState.Modified;
                apply.Status = 2;
                apply.ApplyTime = DateTime.Now;
                db.SaveChanges();
                return RedirectToAction("MyApply");
            }
            return View(apply);
        }

        //删除申请
        [IsLogon]
        [HttpPost]
        public ActionResult DelMyApply(int id)
        {
            try
            {
                var user = Session["users"] as TaoNiuOA.Models.User;
                Apply apply = db.Applies.SingleOrDefault(n => n.ApplyID == id && n.UserID == user.UserID);
                if (apply == null)
                {
                    return Json("您删除的申请不存在");
                }

                if (apply.Status == 1)
                {
                    return Json("您删除的申请已经审批不能删除");
                }

                db.Applies.Remove(apply);
                db.SaveChanges();
                return Json("删除成功");
            }
            catch { return Json("删除失败"); }
        }

        #endregion

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}